<template>
  <a-row>
    <a-col :md="7" :sm="24" v-if="!disabled">
      <!-- <a-spin :spinning="leftLoading">
        <a-directory-tree multiple default-expand-all @select="treeChoose" class="item-btn-mar">

          <a-tree-node title="安徽禾美环保集团有限公司">
            <a-tree-node v-for="(item,index) in leftDataSource" :key="index" :title="item.tdmc" />
          </a-tree-node>
        </a-directory-tree>
      </a-spin> -->
      <a-tabs v-model="collKey" @change="callback">
        <!-- 当为普通级的时候展示公司机构 -->
        <a-tab-pane key="1" tab="公司架构" v-if="!intensiveType || intensiveType == 'ordinary'">
          <div class="item-btn-mar">
            <address-list-left ref="addresslist" @input="treeChoose" />
          </div>
        </a-tab-pane>
        <!-- 当为普通级时展示个人小组 -->
        <a-tab-pane key="2" tab="个人小组" v-if="!intensiveType || intensiveType == 'ordinary'">
          <div class="item-btn-mar">
            <group-list-left ref="grouplist" groupType="personal" @input="groupChoose" />
          </div>
        </a-tab-pane>
        <!-- 任何情况都展示公用小组 -->
        <a-tab-pane key="3" tab="公用小组">
          <div class="item-btn-mar">
            <group-list-left ref="PublicGroupList" groupType="public" @input="groupChoose" />
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-col>
    <!-- 中间区域 -->
    <a-col :md="9" :sm="24" v-if="!disabled">
      <a-form layout="inline" @keyup.enter.native="search">
        <a-row>
          <a-col :span="10">
            <a-form-item label="用户姓名" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <a-input placeholder="请输入用户姓名" v-model="realName" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="部门" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
              <j-select-depart placeholder="请选择部门" v-model="departIds" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item>
              <a-button @click="search" icon="search">查询</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <div class="item-btn-mar">
        <a-table
          ref="table"
          size="middle"
          rowKey="id"
          bordered
          :scroll="{ y: 800 }"
          :columns="columns"
          :dataSource="midDataSource"
          :pagination="ipagination"
          :loading="midLoading"
          :rowSelection="{selectedRowKeys: selectedRowKeys,onSelect:onSelect,onSelectAll:onSelectAll,getCheckboxProps:record => ({
            props: {
              disabled: record.disabled
            }
          })}"
          @change="handleTableChange">

        </a-table>
      </div>
    </a-col>
    <!-- 右侧区域 -->
    <a-col :span="disabled? 24 : 8">
      <div style="height:40px;font-size:16px;display: flex;justify-content: space-between;align-items: center;">
        <span>已选人员</span>
        <a-button v-if="!disabled" @click="addGroup" type="primary">保存为个人小组</a-button>
      </div>
      <div class="item-btn-mar">
        <a-table
          ref="table"
          size="middle"
          rowKey="id"
          bordered
          :scroll="{ y: 800 }"
          :columns="columns"
          :dataSource="selectionRows"
          :pagination="false"
          :loading="rightLoading">

        </a-table>
      </div>
      <a-modal v-model="Gvisible" :width="600" title="新增个人联系人小组">
        <template slot="footer">
          <a-button @click="Gvisible = false">取消</a-button>
          <a-button type="primary" :disabled="isSubmit" @click="handleOk">确认</a-button>
        </template>
        <a-form-model ref="formss" :model="form" :rules="validatorRules">
          <a-row :gutter="48">
            <a-col :span="24">
              <a-form-model-item label="小组名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="groupName">
                <a-input v-model="form.groupName" :max-length="30" placeholder="请输入小组名称"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                <a-textarea :max-length="200" v-model="form.remark" rows="4" placeholder="请输入备注" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-modal>
    </a-col>
  </a-row>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import moment from 'moment'
import { mapGetters } from 'vuex'
import AddressListLeft from '@/views/system/modules/AddressListLeft.vue'
import GroupListLeft from './GroupListLeft.vue'
export default {
  name: 'TeamChoose',
  components: { AddressListLeft, GroupListLeft },
  props: {
    // 区分是通知公告or意见征集
    formType: {
      type: String,
      default: ''
    },
    // 只查看，不能操作
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    publishId: {
      type: String,
      default: ''
    },
    // 选择的密级
    intensiveType: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      collKey: '3',
      Gvisible: false,
      progress: '0', // 流程编号
      leftListUrl: '/api/erp/omc/teammanager/erpOmcTeamManager/list', // 左侧树的list
      findEmpUser: '/api/erpmng/sys/user/queryByOrgCodeForAddressListNew', // 中间获取list
      noticeId: '', // 公告id
      teamId: '', // 团队id
      orgCode: '', // 团队orgCode
      realName: '',
      departIds: '',
      leftLoading: false,
      midLoading: false,
      rightLoading: false,
      columns: [
        {
          title: '序号',
          width: 60,
          dataIndex: 'id',
          align: 'center',
          customRender: function (t, r, index) {
          return parseInt(index) + 1;
          }
        },
        {
          title: '用户部门',
          align: 'center',
          dataIndex: 'departName',
          ellipsis: true
        },
        {
          title: '用户姓名',
          align: 'center',
          dataIndex: 'realname',
          ellipsis: true
        }
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '100'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      leftDataSource: [], // 左侧的list data
      midDataSource: [], // 中间
      selectionRows: [], // 右侧选中的item
      selectedRowKeys: [], // 是否选择的keys
      selectDataList: [], // 获取之前已经选的人
      firstSelectData: [], // 保存一开始的已选人员
      form: {},
      validatorRules: {
        groupName: [
          { required: true, message: '请输入小组名称!' }
        ]
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      groupId: '',
      isSubmit: false
    }
  },
  watch: {
    intensiveType: {
      handler (val) {
        this.collKey = val == 'secret' || val == 'classification' ? '3' : '1'
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    ...mapGetters(['userInfo']),
    search() {
      if (this.collKey == '1') {
        this.getmidList()
      } else {
        this.getmidList2()
      }
    },
    handleTableChange(pagination) {
      this.ipagination.current = pagination.current;
      this.ipagination.pageSize = pagination.pageSize;
      this.search()
    },
    addGroup() {
      if (!this.selectionRows.length) {
        this.$message.warning('请选择小组成员!')
        return
      }
      this.Gvisible = true
      this.isSubmit = false
      this.form = Object.assign({}, {})
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.formss.validate((valid) => {
        if (valid) {
          this.isSubmit = true
          this.form.groupMembers = this.selectionRows.map(v => v.empId).join(',')
          const params = {
            ...this.form,
            groupType: 'personal'
          }
          httpAction('/api/erp/publish/erpPublishContactGroup/add', params, 'post')
            .then((res) => {
              that.Gvisible = false
              if (res.success) {
                that.$message.success(res.message)
                if (that.collKey == '2') {
                  that.$refs.grouplist.commonRequestThen('')
                } else {
                  this.$refs.PublicGroupList.intensiveType = this.intensiveType
                  that.$refs.PublicGroupList.commonRequestThen('')
                }
              } else {
                that.$message.warning(res.message)
              }
              that.isSubmit = false
            })
        }
      })
    },
    callback() {
      if (this.disabled) {
        return
      }
      if (this.collKey == '1') {
        this.$nextTick(() => {
          this.$refs.addresslist.queryTreeData()
        })
      } else if (this.collKey == '2') {
        this.$nextTick(() => {
          this.$refs.grouplist.commonRequestThen('')
        })
      } else {
        this.$nextTick(() => {
          this.$refs.PublicGroupList.intensiveType = this.intensiveType
          this.$refs.PublicGroupList.commonRequestThen('')
        })
      }
    },
    // 左侧树选择
    treeChoose(orgCode) {
      this.orgCode = orgCode
      this.ipagination.current = 1
      this.getmidList()
    },
    groupChoose(id) {
      this.groupId = id || ''
      this.ipagination.current = 1
      if (id) {
        this.getmidList2()
      } else {
        this.midDataSource = []
        this.ipagination.total = 0
      }
    },
    // 单选
    onSelect(record) {
      if (this.selectedRowKeys.includes(record.id)) {
        this.selectedRowKeys = this.selectedRowKeys.filter(it => it != record.id)
        this.selectionRows = this.selectionRows.filter(it => it.id != record.id)
      } else {
        this.selectedRowKeys.push(record.id)
        this.selectionRows.push(record)
      }
    },
    // 全选
    onSelectAll(selected, selectedRows) {
      if (selected) {
        let listAll = JSON.parse(JSON.stringify(this.selectionRows))
        listAll = listAll.concat(this.midDataSource)
        // 去重
        listAll = listAll.filter((item) => !listAll.includes(item.id) && listAll.push(item.id))

        listAll = listAll.filter(r => !r.disabled)

        this.selectionRows = listAll
        this.selectedRowKeys = listAll.map(rr => {
          return rr.id
        })
      } else {
        for (let it of this.midDataSource) {
          this.selectionRows = this.selectionRows.filter(rr => rr.id != it.id)
          this.selectedRowKeys = this.selectedRowKeys.filter(rr => rr != it.id)
        }
      }
      },
    // 左侧团队-分页列表查询
    async getLeftChangeList() {
      this.leftDataSource = []
      this.midDataSource = [] // 进来先清空list里数据

      this.leftLoading = true
      let params = {
        pageNo: 1,
        pageSize: -1,
        tdnd: moment().format('YYYY'),
        teamLevel: '1'
      }
      let res = await getAction(this.leftListUrl, params)
      if (res.success) {
        const { records, current, total } = res.result

        this.leftDataSource = records
      } else {
        this.$message.error(res.message || '列表查询失败！')
        this.leftDataSource = []
      }
      this.leftLoading = false
    },
    // 获取选中的人
    async getSelectDataList() {
      // 判断是通知公告or意见征集
      let url = `/api/erp/${this.formType === 'opinion' ? 'publishCollect' : 'publishNotice'}/findDeptSelectEmpUser`
      let params = {
        noticeId: this.publishId,
        collectId: this.publishId,
        orgCode: this.orgCode,
        pageNo: 1,
        pageSize: -1
      }
      let res = await getAction(url, params)

      if (res.success) {
        this.selectDataList = res.result.records || []
      } else {
        this.$message.error(res.message || '列表查询失败！')
        this.selectDataList = []
      }
    },
    // 中间查询用户信息-列表
    async getmidList2() {
      this.midLoading = true
      let params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        realName: this.realName,
        departIds: this.departIds,
        id: this.groupId
      }
      let res = await getAction('/api/erp/publish/erpPublishContactGroup/queryEmpByGroupId', params)
      if (res.success) {
        let { records, current, total } = res.result

        this.ipagination.total = total || 0

        this.midDataSource = records.map(r => {
          return {
            // id: r.userId,
            disabled: false,
            ...r
          }
        })
        // 获取数据回显
        if (this.selectionRows.length !== 0) {
          for (let it of this.midDataSource) {
            for (let ii of this.selectedRowKeys) {
              if (ii == it.id) {
                it.disabled = false
                this.selectionRows.push(it)
              }
            }
          }
        } else {
          this.selectedRowKeys = []
        }
        this.selectionRows = this.selectionRows.filter((item) => !this.selectionRows.includes(item.id) && this.selectionRows.push(item.id))
      } else {
        this.$message.error(res.message || '列表查询失败！')
        this.midDataSource = []
      }
      this.midLoading = false
    },
    // 中间查询用户信息-列表
    async getmidList() {
      this.midLoading = true
      // await this.getSelectDataList()
      let params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize,
        realname: this.realName,
        departIds: this.departIds,
        orgCode: this.orgCode
      }
      let res = await getAction(this.findEmpUser, params)
      if (res.success) {
        let { records, current, total } = res.result

        this.ipagination.total = total || 0

        this.midDataSource = records.map(r => {
          return {
            id: r.userId,
            disabled: false,
            ...r
          }
        })
        // 获取数据回显
        if (this.selectionRows.length !== 0) {
          for (let it of this.midDataSource) {
            for (let ii of this.selectedRowKeys) {
              if (ii == it.id) {
                it.disabled = false
                this.selectionRows.push(it)
              }
            }
          }
        } else {
          this.selectedRowKeys = []
        }
        this.selectionRows = this.selectionRows.filter((item) => !this.selectionRows.includes(item.id) && this.selectionRows.push(item.id))
      } else {
        this.$message.error(res.message || '列表查询失败！')
        this.midDataSource = []
      }
      this.midLoading = false
    }
  }
}
</script>
<style lang="less">

  .item-btn-mar{
    position: relative;
    height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>
